﻿// Copyright (c) Vitaly Kamiansky. All rights reserved. 
// See License.txt in the project root.

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace Property.Objects
{
    public class ValidationInputProperty<T> : InputProperty<T>, IValidatable, INotifyDataErrorInfo
    {
        protected ValidationInputProperty(IReloaderPrototype<T> reloaderPrototype, Func<T, IEnumerable<string>> validate, T defaultValue)
            : base(reloaderPrototype, defaultValue)
        {
            if (validate == null) throw new ArgumentNullException("validate");

            _Validate = validate;
        }

        //=//

        protected override void ApplyValue(T value)
        {
            base.ApplyValue(value);
            Validate();
        }

        public void Validate()
        {
            ValidationErrorsState = _Validate(Input);
            OnErrorsChanged("Input");
        }

        private readonly Func<T, IEnumerable<string>> _Validate;

        private IEnumerable<string> ValidationErrorsState;

        public bool HasErrors 
        { 
            get 
            {
                return new[] { ValidationErrorsState }
                    .OfType<IEnumerable<string>>()
                    .Select(o => o.Any())
                    .FirstOrDefault();
            } 
        }

        public IEnumerable GetErrors(string propertyName)
        {
            return new[] { propertyName }
                .Where(o => o == "Input")
                .Select(_ => ValidationErrorsState)
                .FirstOrDefault();
        }

        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

        protected void OnErrorsChanged(string propertyName)
        {
            if (ErrorsChanged != null)
                ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }
    }
}
